// pages/invalid-time/index.js
import {
  request
} from '../../api/index'
import moment from 'moment';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    time: '',
    currentDate: '3:00',
    minHour: 0,
    maxHour: 48,
    show: false,
    root: false
  },
  setPageOption() {
    wx.setNavigationBarTitle({
      title: '设置采集记录有效时间'
    })
  },
  fetchData() {
    const settingKey = 'COLLECTION_RECORD_SETTINGS',
      key = 'invalidTime';
    request.getSingleSetting({
      settingKey: settingKey
    }, res => {
      if (res.settingData) {
        const data = res.settingData.find(it => it.key === key),
          tempTime = moment.duration(Number(data.value), 'seconds'),
          time = tempTime.hours() + '小时' + tempTime.minutes() + '分钟',
          currentDate = tempTime.hours() + ':' + tempTime.minutes();
        this.setData({
          time,
          currentDate
        })
      }
    })
  },
  onInput(event) {
    this.setData({
      currentDate: event.detail,
    });
  },
  onTimeClose() {
    this.setData({
      show: false
    })
  },
  onTimeShow() {

    this.setData({
      show: this.data.root
    })
  },
  onConfirm(event) {
    const ftime = event.detail;
    const hh = Number(ftime.slice(0, 2)),
      mm = Number(ftime.slice(3, 5));
    const ss = hh * 60 * 60 + mm * 60;
    this.modifyTime(ss);
  },
  modifyTime(time) {
    if (time === 0) {
      wx.showToast({
        title: '时长不可为0',
        icon: 'error'
      })
      return
    }
    request.updateSingleSetting({
      settingData: [{
        key: "invalidTime",
        value: time
      }],
      settingKey: 'COLLECTION_RECORD_SETTINGS'
    }, this.fetchData.bind(this))
    this.onTimeClose();
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setPageOption();
    this.fetchData()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    const app = getApp();
    this.setData({
      root: app.globalData.root
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})